/**
 * 
 */
package com.ydy.service.staff.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydy.constant.SystemConstant;
import com.ydy.exception.BusinessException;
import com.ydy.exception.DataNotFoundException;
import com.ydy.exception.ValidateException;
import com.ydy.ienum.EnumShop;
import com.ydy.ienum.EnumStaff;
import com.ydy.ienum.EnumSystem;
import com.ydy.mapper.ShopMapper;
import com.ydy.mapper.StaffMapper;
import com.ydy.model.Shop;
import com.ydy.model.Staff;
import com.ydy.service.staff.StaffService;
import com.ydy.utils.Md5Util;
import com.ydy.utils.TokenUtil;
import com.ydy.utils.ValidateUtil;
import com.ydy.vo.other.BaseVo;
import com.ydy.vo.other.PageVo;
import com.ydy.vo.other.ResultVo;
import com.ydy.vo.token.StaffTokenVo;

/**
 * @author xuzhaojie
 *
 *         2019年5月29日 上午8:35:26
 */
@Service
@Transactional
public class StaffServiceImpl implements StaffService {
	private final static Logger log = LoggerFactory.getLogger(StaffServiceImpl.class);

	@Autowired
	private StaffMapper staffMapper;
	@Autowired
	private ShopMapper shopMapper;

	@Override
	public PageVo<Staff> select(Staff staff, Integer page, Integer size) {
		PageVo<Staff> vo = new PageVo<Staff>(page, size);
		Page<Staff> pageBean = PageHelper.startPage(vo.getPage(), vo.getSize(), "id desc");
		List<Staff> list = staffMapper.selectData(staff);
		vo.setTotal(pageBean.getTotal());
		vo.setList(list);
		return vo;
	}

	@Override
	public PageVo<Staff> selectByShopId(Staff staff, Long shopId, Integer page, Integer size) {
		PageVo<Staff> vo = new PageVo<Staff>(page, size);
		Page<Staff> pageBean = PageHelper.startPage(vo.getPage(), vo.getSize(), "id desc");
		staff.setShopId(shopId);
		List<Staff> list = staffMapper.selectData(staff);
		vo.setTotal(pageBean.getTotal());
		vo.setList(list);
		return vo;
	}

	@Override
	public StaffTokenVo checkStaff(Staff staff) {
		Staff temp = null;
		Staff record = new Staff();
		record.setUsername(staff.getUsername());
		List<Staff> list = staffMapper.select(record);
		if (list.size() <= 0) {
			log.info("找不到该staff:" + staff.getUsername());
			throw new DataNotFoundException(EnumStaff.DATA_NOT_FOUND);
		}
		temp = list.get(0);
		if (temp == null || !Objects.equals(Md5Util.getMD5(staff.getPassword()), temp.getPassword())) {
			log.info("staff登录密码错误:" + staff.getUsername());
			throw new BusinessException(EnumStaff.PWD_ERROR);
		}
		if (SystemConstant.USE_STATUS_OFF.equals(temp.getUseStatus())) {
			log.info("staff不可用:" + staff.getUsername());
			throw new BusinessException(EnumStaff.CAN_NOT_USE_STATUS);
		}
		Shop shop = shopMapper.selectByPrimaryKey(temp.getShopId());
		if (shop == null || !(SystemConstant.USE_STATUS_ON.equals(shop.getOnStatus()))) {
			throw new BusinessException(EnumShop.SHOP_CAN_NOT_USE);
		}
		String token = TokenUtil.createStaffToken(temp);
		StaffTokenVo vo = new StaffTokenVo();
		vo.setStoken(token);
		vo.setTimestamp(System.currentTimeMillis());
		return vo;
	}

	@Override
	public Staff saveOrUpdate(Staff staff) {
		if (staff == null) {
			throw new NullPointerException();
		}
		// 校验数据有效
		Map<String, String> validateInfo = ValidateUtil.validateEntity(staff);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		Shop shop = shopMapper.selectByPrimaryKey(staff.getShopId());
		if (shop == null) {
			throw new DataNotFoundException(EnumShop.DATA_NOT_FOUND);
		}
		// 新增staff信息
		String username = "STAFF." + staff.getUsername();// 同步，防止同时对一个staff进行修改
		synchronized (username.intern()) {
			if (staff.getId() == null) {
				Staff record = new Staff();
				record.setUsername(staff.getUsername());
				List<Staff> list = staffMapper.select(record);
				if (list.size() > 0) {// 用户名已存在
					throw new BusinessException(EnumStaff.USERNAME_EXSIT);
				}
				staff.setPassword(Md5Util.getMD5(staff.getPassword()));// 设置默认密码
				staff.setUseStatus(SystemConstant.USE_STATUS_ON);
				staff.setRegTime(new Date());
				staffMapper.insertSelective(staff);
				log.info("新增staff信息成功:" + staff.getUsername());
			} else {// 根据id更新信息
				Staff temp = staffMapper.selectByPrimaryKey(staff.getId());
				if (temp == null) {// 不存在该id信息
					throw new DataNotFoundException(EnumStaff.ADMIN_NOT_FOUND);
				}
				staff.setShopId(null);
				staff.setUsername(null);// 不能修改用户名
				staff.setPassword(null);// 不能修改密码
				staff.setRegTime(null);// 不能修改注册时间
				staffMapper.updateByPrimaryKeySelective(staff);
				// 要返回这个字段
				staff.setUsername(temp.getUsername());
				staff.setShopId(temp.getShopId());
				staff.setRegTime(temp.getRegTime());
				log.info("修改staff信息成功:" + staff.getUsername());
			}
		}
		return staff;
	}

	@Override
	public BaseVo modifyPassword(Long id, String username, String password, String newPassword) {
		if (id == null) {
			throw new NullPointerException();
		}
		Staff staff = staffMapper.selectByPrimaryKey(id);
		if (staff == null) {
			log.info("找不到staff信息:" + id);
			throw new DataNotFoundException(EnumStaff.DATA_NOT_FOUND);
		}
		if (!(Objects.equals(username, staff.getUsername())
				&& Objects.equals(Md5Util.getMD5(password), staff.getPassword()))) {
			log.error("用户名密码不匹配:" + id);
			throw new BusinessException(EnumStaff.PWD_ERROR);
		}
		Staff update = new Staff();
		update.setId(id);
		update.setPassword(Md5Util.getMD5(newPassword));
		staffMapper.updateByPrimaryKeySelective(update);
		return new ResultVo();
	}

	@Override
	public BaseVo resetPassWord(Long id) {
		BaseVo vo = null;
		Staff staff = staffMapper.selectByPrimaryKey(id);
		if (staff == null) {
			throw new DataNotFoundException(EnumStaff.DATA_NOT_FOUND);
		}
		Staff temp = new Staff();
		temp.setId(id);
		temp.setPassword(Md5Util.getMD5("123456a"));// 设置初始密码
		staffMapper.updateByPrimaryKeySelective(temp);
		log.info("设置初始密码成功:" + staff.getUsername());
		vo = new ResultVo(EnumSystem.SUSS);
		return vo;
	}

	@Override
	public BaseVo updateUseStatus(Long id) {
		BaseVo vo = null;
		Staff staff = staffMapper.selectByPrimaryKey(id);
		if (staff != null) {
			Staff temp = new Staff();
			temp.setId(id);
			if (SystemConstant.USE_STATUS_ON.equals(staff.getUseStatus())) {
				temp.setUseStatus(SystemConstant.USE_STATUS_OFF);
			} else {
				temp.setUseStatus(SystemConstant.USE_STATUS_ON);
			}
			staffMapper.updateByPrimaryKeySelective(temp);
			vo = new ResultVo(EnumSystem.SUSS);
		} else {
			throw new BusinessException(EnumStaff.ADMIN_NOT_FOUND);
		}
		return vo;
	}

	@Override
	public Staff selectById(Long id) {
		if (id == null) {
			throw new NullPointerException();
		}
		Staff staff = staffMapper.selectByPrimaryKey(id);
		if (staff != null) {
			return staff;
		} else {
			throw new BusinessException(EnumStaff.DATA_NOT_FOUND);
		}
	}

}
